package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.BootstrapText;
import com.beardedhen.androidbootstrap.api.view.BootstrapTextView;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.infore.airsupervise.R;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.bean.LawingSiteE;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.SiteLawingBiz;
import com.infore.airsupervise.biz.impl.SiteLawingBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.widget.SwipeRecyclerView;
import com.infore.airsupervise.utils.JumpUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 执法台账列表 /查询界面
 * Created by xiaotao on 2017/5/26.
 */

public class SiteLedgerListActivity extends BaseTitleBarActivity implements SwipeRecyclerView.OnActionListener {

    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_searchClean)
    ImageView ivSearchClean;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.refreshRecyclerView)
    SwipeRecyclerView recyclerView;
    @BindView(R.id.common_search_bar)
    LinearLayout commonSearchBar;

    private List<LawingSiteE> datas = new ArrayList<>(); //台账集合
    private BaseQuickAdapter<LawingSiteE, BaseViewHolder> adapter;

    private SiteLawingBiz siteLawingBiz;
    private String userId;

    private String keyWord;
    private String queryMn;
    private int pageNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_polluter_search);
        ButterKnife.bind(this);
        siteLawingBiz = new SiteLawingBizImpl();
        userId = UserE.getUserInfo().getUserId();
        Intent it = getIntent();
        if (null != it) {
            queryMn = getIntent().getStringExtra(Constants.INTENT_STR_KEY);
            //如果 mn号不为空则判断是从污染源详情界面跳转来的
            if (null != queryMn) {
                initRecordTitle();
            } else {
                initTitle();
            }
        }
        initRecyclerView();

    }

    /**
     *
     */
    private void initRecordTitle() {
        title.setText("执法记录列表");
        rightMenu.setVisibility(View.GONE);
        commonSearchBar.setVisibility(View.GONE);
    }

    /**
     *
     */
    private void initTitle() {
        title.setText("执法台账");
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_FILTER);
        //etSearch.setHint("");
        tvSearch.setText("搜索");
        // 键盘搜索按钮监听
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return false;
            }
        });
    }

    /**
     * 列表
     */
    private void initRecyclerView() {
        //适配器
        adapter = new BaseQuickAdapter<LawingSiteE, BaseViewHolder>(R.layout.item_license_list, datas) {
            @Override
            protected void convert(BaseViewHolder helper, LawingSiteE item) {
                helper.setText(R.id.company_name, item.getName())
                        .setText(R.id.license_code, item.getTime());
                BootstrapTextView icon = helper.getView(R.id.titlebar_right_menu);
                BootstrapText.Builder builder = new BootstrapText.Builder(ctx);
                builder.addFontAwesomeIcon(FontAwesome.FA_BOOK);
                icon.setBootstrapText(builder.build());
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.setActionListener(this);
        // 首次自动刷新
        recyclerView.getSwipeLayout().setRefreshing(true);
        recyclerView.onRefresh();
    }

    /**
     * 搜索框是否可用
     *
     * @param enabled
     */
    private void searchBarEnable(boolean enabled) {
        tvSearch.setEnabled(enabled);
        etSearch.setEnabled(enabled);
        ivSearchClean.setEnabled(enabled);
    }

    /**
     * 获取台账列表数据的请求
     *
     * @param isRefresh
     */
    private void getLedgerData(final boolean isRefresh) {
        searchBarEnable(false);
        Call call = siteLawingBiz.sendSiteLedgerListRequest(etSearch.getText().toString(), queryMn, pageNum, userId, new OnServerResponseListener<List<LawingSiteE>>() {
            @Override
            public void onSucceed(List<LawingSiteE> result, String desc) {
                recyclerView.commonSuccessHandle(isRefresh, result.size());
                if (isRefresh) {
                    datas.clear();
                }
                pageNum++;
                datas.addAll(result);
                adapter.notifyDataSetChanged();
                searchBarEnable(true);
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                recyclerView.commonFailedHandle(isRefresh, errorCode, title, desc);
                searchBarEnable(true);
            }
        });
        requests.add(call);
    }


    @OnClick({R.id.tv_search,R.id.iv_searchClean})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tv_search:
                recyclerView.getSwipeLayout().setRefreshing(true);
                recyclerView.onRefresh();
                break;
            case R.id.iv_searchClean :
                etSearch.getText().clear();
                break;
        }

    }

    /**
     * 选择关键字类型的菜单
     *
     * @param view
     */
    @Override
    protected void onRightMenuClick(View view) {
        super.onRightMenuClick(view);
        PopupMenu popupMenu = null;
        popupMenu = new PopupMenu(ctx, rightMenu);
        popupMenu.inflate(R.menu.site_ledger_query_menu);
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                String hint = "搜索" + item.getTitle();
                switch (item.getItemId()) {
                    case R.id.menu_pson:
                        break;
                    case R.id.menu_site:
                        break;
                }
                etSearch.setHint(hint);
                return true;
            }
        });
        popupMenu.show();
    }


    @Override
    public void onRefresh() {
        pageNum = 1;
        getLedgerData(true);
    }

    @Override
    public void onLoadMore() {
        getLedgerData(false);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        //到详情界面
        JumpUtil.jumpFromTo(this, SiteMainDetailActivity.class, Constants.INTENT_OBJ_KEY, datas.get(position));
    }

}
